<template>
	<view>
		<u-navbar title="编辑用户号" :border-bottom="false">
			<!-- <view class="u-m-r-30" slot="right">
				<text class="text-theme u-font-32" >保存</text>
			</view> -->
			<view slot="right" class="u-p-x-16 u-p-y-4 u-m-r-30 radius" @tap="save" :class="{'bg-grey':!valid,'bg-blue':valid}">
				<text class="u-font-28">保存</text>
			</view>
		</u-navbar>
		<view class="u-m-30">
			<view class="from u-m-t-20">
				<view class="group">
					<input v-model="text" class="u-flex-1 u-font-32" placeholder="请输入用户号" @input="onInput"/>
					<text class="u-font-32 text-gray" v-if="text">{{byte}}/{{maxByte}}</text>
				</view>
			</view>
			<view class="u-m-t-20">
				<text class="u-font-28 text-gray">{{minByte}}-{{maxByte}}个字符，仅可使用英文（必须）、数字、下划线组合</text>
			</view>
		</view>
	</view>
</template>

<script>
	const nickReg = /^(?=.*[a-zA-z])[a-zA-Z0-9_]{6,15}$/;
	import {goback, toast} from "@/utils/util.js"
	import {getStringByte} from "@/utils/check.js"
	import {modifyUser} from "@/api/user.js"
	import {mapGetters,mapMutations} from "vuex"
	export default {
		data() {
			return {
				text:'',
				minByte:6,
				maxByte:15,
			};
		},
		computed:{
			...mapGetters('user',['userInfo']),
			byte(){
				return getStringByte(this.text)
			},
			valid(){
				if(this.text==this.userInfo.userNum){
					return false
				}
				if(!nickReg.test(this.text)){
					return false
				}
				if(this.byte<this.minByte||this.byte>this.maxByte){
					return false
				}
				return true
			}
		},
		onLoad() {
			this.text = this.userInfo.userNum
		},
		methods:{
			...mapMutations('user',['mixUserInfo']),
			onInput({detail:{value}}){
				const txt = value.split('').reduce((r,i)=>{
					if(getStringByte(r+i)<=this.maxByte){
						r+=i
					}
					return r
				},'')
				this.$nextTick(()=>{
					this.text = txt
				})
			},
			async save(){
				if(!this.valid){
					return
				}
				if(this.save.lock){
					throw new Error('正在请求中')
				}
				try{
					this.save.lock = true
					const userNum = this.text
					await modifyUser({
						userNum
					})
					this.mixUserInfo({userNum})
					goback()
				}catch(e){
					toast(e.data.retDesc)
				}finally{
					this.save.lock = false
				}
			}
		}
	}
</script>

<style>
	page{
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
	.opacity-50{
		opacity:0.5
	}
	.from{
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 0 30rpx;
		.group{
			padding: 20rpx 0rpx;
			display: flex;
		}
	}
	
</style>

